add_library('net')
c = Client(this, '127.0.0.1',12346)
w,h = 800,400
me = {'pos':(0,0),'bubble':[]}
import json
def setup():
    size(780, h + 65)
    background(204)
    stroke(0)
    frameRate(60)
    
def draw():
    background(204)
    stroke(0)
    for i in range(20):
        line(i*40,0,i*40,h)
    for i in range(20):
        line(0,i*40,w,i*40)
                
    response = c.available()
    if response >0:
        print('!!resp>0')
        inp = c.readString()
        inps = inp.split('\r\n')
        print(inps)
        for inp in inps:
            print('for',inp)

            if 'data' in inp:
                print('operation',inp)
                #inp = inp.decode('utf-8')
                inp = inp.replace('\r','')
                data = json.loads(inp)
                print(data['data'])
                me.update(data['data'])
            elif 'pos:' in inp  :
                pos = inp[4:].replace('\r','')
                print('pos',pos)
                x,y = pos.split(',')
                me['pos'] = (float(x),float(y))
                
    stroke(0,255,0)
    fill(255,100)
    rect( me['pos'][0], me['pos'][1],40,40)
    
    for x,y in me['bubble']:
        fill(0,0,255)
        rect( 40* x,40*y,40,40)
    # else:
    #     print('no resp>0')
def move(current_direction,v,pos):
    dirs = ['left', 'right', 'up', 'down']

    r = dirs.index(current_direction)

    ds = [(-v, 0), (v, 0), (0, -v), (0, v)]
    dx, dy = ds[int(r)]
    x,y = pos
    return x+dx,y+dy
            
def keyPressed():
    global player2
    #print("typed %s %d" % (key, keyCode))
    dir = ''
    if key == CODED:
        
        if keyCode == UP:
            dir = 'up'
            
        elif keyCode == DOWN:
            dir = 'down'
        elif keyCode == LEFT:
            dir = 'left'
        elif keyCode == RIGHT:
            dir = 'right'
    if key == 'j':
        c.write(json.dumps({'operation':'put_bubble'})+"\n")
    m = {'a': 'left', 'd': 'right', 'w': 'up', 's': 'down'}
    for k,current_direction in m.items():
        if k== key:
            
            me['pos']= move(current_direction,4, me['pos'])
    if dir !='':
        print('send',dir)
        c.write(dir+"\n")